#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import json
import webbrowser
import urllib
import datetime
import pathlib
import os

import requests
import lxml.html
import click as cli

LINK_CORREIOS_URL = 'https://www.linkcorreios.com.br'
HOME = str(pathlib.Path.home())
CORREIOS_CLI_FILE = os.path.join(HOME, '.correios_cli')
DATE_FORMAT = '%d/%m/%Y %H:%M'

url_object = None


class Session(object):
    def __init__(self):
        self.session = requests.Session()

    def get(self, url, **kwargs):

        headers = {
            'user-agent': (
                'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:67.0) '
                'Gecko/20100101 Firefox/67.0')}

        return self.session.get(
            url=url,
            headers=headers,
            **kwargs)

session = Session()

def get_object_page(object_code):

    global url_object

    url_object = urllib.parse.urljoin(LINK_CORREIOS_URL, object_code)

    object_page_response = session.get(url_object)

    return lxml.html.fromstring(object_page_response.text)

def str_to_datetime(str_date):
    return datetime.datetime.strptime(str_date, DATE_FORMAT)

def datetime_to_str(datetime_date):
    return datetime.datetime.strftime(datetime_date, DATE_FORMAT)

def get_dates(object_page_html):

    dates_tds = object_page_html.xpath('//td[@rowspan=2]')

    datetime_dates = list()

    for date_td in dates_tds:
        str_date = date_td.text

        datetime_date = str_to_datetime(str_date)

        datetime_dates.append(datetime_date)

    return datetime_dates

def get_last_registry(dates, object_code):

    last_registry_date = ''

    try:
        with open(CORREIOS_CLI_FILE, 'r+') as correios_cli_file_open:
            last_registry_date = correios_cli_file_open.read()
    except FileNotFoundError:
        print('Creating new registry.')

        with open(CORREIOS_CLI_FILE, 'w') as new_registry_file:
            str_max_date = datetime_to_str(max(dates))
            new_registry_file.write(str_max_date)
            last_registry_date = str_max_date

    return last_registry_date

def check_object_status(object_code):

    object_page_html = get_object_page(object_code)

    dates = get_dates(object_page_html)

    last_registry = get_last_registry(dates, object_code)

    max_date = max(dates)

    if max_date > str_to_datetime(last_registry):
        webbrowser.open(url_object)

        new_max_date_found_str = datetime_to_str(max_date)

        with open(CORREIOS_CLI_FILE, 'w') as renewed_registry_file:
            renewed_registry_file.write(new_max_date_found_str)

        print('New status found. Opening browser...')

        print(new_max_date_found_str)

        return

    print('No changes since last verification.')

    print(last_registry)

@cli.command()
@cli.option('--code', help='Object code', required=True)
def check_object_cli(code):
    check_object_status(code)

if __name__ == '__main__':
    check_object_cli()
